package org.akomantoso.core.data;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.akomantoso.core.data.group.PreambleContainers;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.Output;

/**
 * The element citation is the individual element of the preface that is called citation.
 * 
 * <pre>
 * 	<xsd:element name="citations">
 * 		<xsd:complexType>
 * 			<xsd:sequence>
 * 				<xsd:element ref="intro" minOccurs="0" maxOccurs="1"/>
 * 				<xsd:element ref="citation" minOccurs="1" maxOccurs="unbounded"/>
 * 			</xsd:sequence>
 * 			<xsd:attributeGroup ref="coreopt"/>
 * 		</xsd:complexType>
 * 	</xsd:element>
 * </pre>
 * 
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 * 
 */
public final class Citations extends CoreOptImpl implements PreambleContainers{

	public static final String ELEMENT = "citations";
	
	// Optional
	private Intro _intro;
	
	// Mandatory (min 1).
	private final List<Citation> _citations = new ArrayList<Citation>();
	
	/**
	 * @see org.akomantoso.core.io.Externalizable#writeExternal(org.akomantoso.core.io.Output)
	 */
	@Override
	public <T extends Output> void writeExternal(T out) throws IOException {
		out.writeStart(ELEMENT);
		super.writeExternal(out);
		if (_intro != null) {
			_intro.writeExternal(out);
		}
		for (Citation citation : _citations) {
			citation.writeExternal(out);
		}
		out.writeEnd();
	}

	/**
	 * @see org.akomantoso.core.io.Externalizable#readExternal(org.akomantoso.core.io.Input)
	 */
	@Override
	public <T extends Input> void readExternal(T in) throws IOException {
		super.readExternal(in);
		
		in.readNextStartOrEndElement();
		
		if (Intro.ELEMENT.equals(in.getLocalName())) {
			_intro = new Intro();
			_intro.readExternal(in);
			in.readNextStartOrEndElement();
		}
		
		Citation citation;
		while (Citation.ELEMENT.equals(in.getLocalName())) {
			_citations.add(citation = new Citation());
			citation.readExternal(in);
			in.readNextStartOrEndElement();
		}
	}
	
	
}